import snac
import vars
import binascii
from snac import *
from vars import *
from binascii import hexlify

class flap():
    id = ""
    channel = ""
    sequence = ""
    dataSize = ""
    SNAC = snac()

    def __init__(self):
        self.id = "2a"
        self.channel = "02"
        self.sequence = "%X"% vars.seq
        self.sequence = self.sequence.zfill(4)
        self.dataSize = "0000"
        SNAC = snac()
 

    #Parses a flap packet, sends the snac portion to be read
    def readFlap(self,packet):
        count = 0
        while len(packet) > 0:

            
            self.id = packet[0:2]
            self.channel = int(packet[2:4], 16)                    
            self.sequence =  int(packet[4:8], 16)
            self.dataSize = int(packet[8:12], 16)
            if (self.dataSize*2 > len(packet) - 12):
        
                return packet

            if(self.dataSize > 0):
        
                self.SNAC.readSnac(packet[12:12+2*(self.dataSize)])
        

            #Keeps track of first flap in a multiflap packet
            if count == 0:
                vars.firstFam = self.SNAC.family
                vars.firstType = self.SNAC.subtype
            
            if(self.dataSize > 4):
                count = count + 1
                
            packet = packet[12+2*(self.dataSize):len(packet)]
        return None
    
    #Printable version of flap
    def __str__(self):
        return "Id : "+ str(self.id) +"\nChannel: "+ str(self.channel) + "\nSequence: "+str(self.sequence) +"\nDataSize:"+ str(self.dataSize)+str(self.SNAC)
    

    #Packs a flap for writing, makes sure the data size is consistent
    def pack(self):
        self.dataSize = self.SNAC.getSize().zfill(4)
        return str(self.id)+str(self.channel)+str(self.sequence)+str(self.dataSize) + self.SNAC.pack()
    
    #creates a generic flap packet
    def writeFlap(self, channel):
        self.id = "2a"
        self.channel = channel
        self.sequence = "%X" %vars.flapseq 
        self.sequence = self.sequence.zfill(4)
        self.dataSize = 0

    
    #Used to print the contents of a standard message
    def printMessage(self):
        tlvs = self.SNAC.getMessage()
        for ii in range(0,len(tlvs)):
            if (tlvs[ii][0] == "0002"):
                print tlvs[ii][2][8:len(tlvs[ii][2])]
        

    
